package com.example.shop_front_api.controller;

import com.example.shop_front_api.entity.Members;
import com.example.shop_front_api.service.MembersService;
import com.example.shop_front_api.utils.JsonResult;
import com.example.shop_front_api.utils.Md5Utils;
import com.example.shop_front_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/members")
public class MemberController {
    @Autowired
    private MembersService membersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Members members;
    @PostMapping("register")
    public JsonResult register(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        //重复性验证
        Members membersInfo = membersService.getMembersByUsername(mobile);
        if (membersInfo != null) {
            return JsonResult.failed("该手机号码已经使用，请更换.");
        }
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        members.setMobile(mobile);
        members.setUsername(mobile);
        members.setRegisteredTime(Tool.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        System.out.println(members);
        int result = membersService.insertMembers(members);
        if (result == 0) {
            return JsonResult.failed("注册失败");
        }
        //删除缓存验证码
        stringRedisTemplate.delete(mobile);
        return JsonResult.success("注册成功",null);
    }

    //获取短信验证码
    @PostMapping("get_sms_code")
    public JsonResult getSMSCode(@RequestParam("mobile") String mobile) {
        //验证手机号格式
        if (mobile == null || mobile.trim().isEmpty() || !Tool.isMobile(mobile)) {
            return JsonResult.failed("请输入正确格式的手机号码");
        }
        //生成4位数字随机验证码
        long randomNum = Tool.generateRandomNumber(4);
        //String message = "【上海星知心教育科技】您的验证码是"+randomNum+",1分钟内有效。若非本人操作请忽略此消息";
        //调用短信接口
        //SMSUtils.sendSms(mobile, message);
        //存储到redis
        stringRedisTemplate.opsForValue().set(mobile, String.valueOf(randomNum),60*60, TimeUnit.SECONDS);
        return JsonResult.success("获取成功",randomNum);
    }


    @PostMapping("login")
    public JsonResult login(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        Members memberInfo = membersService.getMembersByUsername(mobile);
        if (memberInfo == null) {
            return JsonResult.failed("登录失败");
        }

        //删除缓存验证码
        stringRedisTemplate.delete(mobile);
        HashMap<String, Object> mapMemberInfo = new HashMap<>();
        mapMemberInfo.put("id", memberInfo.getId());
        mapMemberInfo.put("username", memberInfo.getUsername());
        mapMemberInfo.put("mobile", memberInfo.getMobile());
        return JsonResult.success("登录成功",mapMemberInfo);
    }

    @PostMapping("update_password")
    public JsonResult updatePassword(@RequestParam("mobile") String mobile,
                                     @RequestParam("code") String code,
                                     @RequestParam("password") String password,
                                     @RequestParam("confirm_password") String confirmPassword
    ) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("请输入密码.");
        }
        //验证密码格式
        if (!Tool.isValidPassword(password)) {
            return JsonResult.failed("输入密码格式不正确.");
        }

        if (!password.equals(confirmPassword)) {
            return JsonResult.failed("两次输入密码不一致.");
        }
        String safePassword = Md5Utils.encrypt(password);
        int result = membersService.updatePassword(mobile, safePassword);
        if (result == 0) {
            return JsonResult.failed("设置成功");
        }

        //删除缓存验证码
        //stringRedisTemplate.delete(mobile);
        return JsonResult.success("设置成功",null);
    }


    @PostMapping("update_pay_password")
    public JsonResult updatePayPassword(@RequestParam("id") int id,
                                        @RequestParam("password") String password,
                                        @RequestParam("confirm_password") String confirmPassword
    ) {

        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("请输入密码.");
        }
        //验证密码格式
        if (!Tool.isValidPassword(password)) {
            return JsonResult.failed("输入密码格式不正确.");
        }

        if (!password.equals(confirmPassword)) {
            return JsonResult.failed("两次输入密码不一致.");
        }
        String safePassword = Md5Utils.encrypt(password);
        int result = membersService.updatePayPassword(id, safePassword);
        if (result == 0) {
            return JsonResult.failed("设置成功");
        }
        return JsonResult.success("设置成功",null);
    }

    @PostMapping("check_mobile")
    public JsonResult checkMobile(@RequestParam("id") int id, @RequestParam("mobile") String mobile) {

        Members memberInfo = membersService.getMembersById(id);
        if (memberInfo == null) {
            return JsonResult.failed("该用户不存在");
        }
        if(!memberInfo.getMobile().equals(mobile)){
            return JsonResult.failed("原手机号码输入错误");
        }

        //生成4位数字随机验证码
        long randomNum = Tool.generateRandomNumber(4);
        //String message = "【上海星知心教育科技】您的验证码是"+randomNum+",1分钟内有效。若非本人操作请忽略此消息";
        //调用短信接口
        //SMSUtils.sendSms(mobile, message);
        //存储到redis
        stringRedisTemplate.opsForValue().set(mobile, String.valueOf(randomNum),60*60, TimeUnit.SECONDS);
        return JsonResult.success("获取成功",randomNum);
    }

    @PostMapping("check_code")
    public JsonResult checkCode(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        //stringRedisTemplate.delete(mobile);
        return JsonResult.success("验证通过",null);
    }

    @PostMapping("update_mobile")
    public JsonResult updateMobile(@RequestParam("id") int id,
                                   @RequestParam("mobile") String mobile,
                                   @RequestParam("code") String code
    ) {

        //验证手机号格式
        if (mobile == null || mobile.trim().isEmpty() || !Tool.isMobile(mobile)) {
            return JsonResult.failed("请输入正确格式的手机号码");
        }

        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }

        //验证手机号重复
        Members membersInfo = membersService.getMembersByMobile(mobile);
        if (membersInfo != null && id != membersInfo.getId()) {
            return JsonResult.failed("该手机号已经占用，请更换.");
        }
        int result = membersService.updateMobile(id, mobile);
        if (result == 0) {
            return JsonResult.failed("设置失败");
        }
        return JsonResult.success("设置成功",null);
    }


}
